package com.mxn.soul.flowingdrawer;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.*;

import com.kaopiz.kprogresshud.KProgressHUD;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by weijie.liu on 17/04/2017.
 */

public class CourseListActivity extends AppCompatActivity {
    //相关工具类
    private URLData urlData = null;
    private HtmlParseJson htmlParseJson = null;

    //数据库类
    private MySQLiteOpenHelper mHelper;
    private SQLiteDatabase mDb;

    //相关map list 用于存储数据
    private Handler handler;
    private Map myMap = new HashMap();
    private List<String> teachNameitems = new ArrayList<>();
    private ArrayList<ClassInfo1> Info1List = new ArrayList<>();

    //学期及其相关控件
    private String[][] getxq = new String[][]{
            {"2016-2017学年第二学期", "20161"},
            {"2016-2017学年第一学期", "20160"},
            {"2015-2016学年第二学期", "20151"},
            {"2015-2016学年第一学期", "20150"},
            {"2014-2015学年第二学期", "20141"},
            {"2014-2015学年第一学期", "20140"},
    };
    String xqValue = "";
    Spinner spin_xqname = null;

    //教师姓名及其相关控件
    String techname_edit = "";
    EditText edit_teacherName = null;
    String technameValue = "";
    Spinner spin_techname = null;

    //验证码及其相关
    ImageView imgv_yzm = null;
    EditText edit_yzm = null;
    String yzm_edit = "";
    Bitmap bitmap_img = null;

    Toolbar mToolbar;

    FloatingActionButton mFabSearch;

    EditText mEditText;

    Spinner mSpinner;

    RecyclerView mRecyclerView;

    FloatingActionButton mFabUp;

    KProgressHUD loading;

    private CourseAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course);


        //获获取控件
        spin_xqname = (Spinner) findViewById(R.id.spinner_xq);
        edit_teacherName = (EditText) findViewById(R.id.edit_kcName);
        imgv_yzm = (ImageView) findViewById(R.id.imgv_yzm);
        spin_techname = (Spinner) findViewById(R.id.spiner_kcName);
        edit_yzm = (EditText) findViewById(R.id.edit_yzm);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mFabSearch = (FloatingActionButton) findViewById(R.id.fab);
        //-------
        mEditText = (EditText) findViewById(R.id.edit_kcName);

        //------
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mFabUp = (FloatingActionButton) findViewById(R.id.fab_up);


        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);

        mAdapter = new CourseAdapter(CourseListActivity.this);

        mRecyclerView.setAdapter(mAdapter);
        mEditText.requestFocus();
        loading = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setDetailsLabel("加载中")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f);

        //初始化 学期 教师姓名 验证码
        String xq_spin = spin_xqname.getSelectedItem().toString();
        for (int i = 0; i < getxq.length; i++) {
            if (xq_spin.equals(getxq[i][0]))
                xqValue = getxq[i][1];
        }
        techname_edit = edit_teacherName.getText().toString(); //获取输入的教师姓名
        getListName("1");


        //refresh yzm
        imgv_yzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getListName("1");
            }
        });

        //datebase
        mHelper = new MySQLiteOpenHelper(this, "course_table.db", null, 1);
        mDb = mHelper.getWritableDatabase();


        //handler
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                loading.dismiss();
                if (msg.what == 1) {

                    imgv_yzm.setImageBitmap(bitmap_img);

                    for (Object s : myMap.keySet()) {
                        teachNameitems.add(myMap.get(s).toString());
                    }
                    ArrayAdapter<String> kcAdapter = new ArrayAdapter<String>(CourseListActivity.this, android.R.layout.simple_spinner_item, teachNameitems);
                    kcAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spin_techname.setAdapter(kcAdapter);//下拉列表显示
                } else if (msg.what == 2) {
                    mAdapter.setCourseData(Info1List);
                    //界面显示之后存入数据库
                    addInfoToSqlite();

                    ////else 后绑定下边的 数据是Info1List
                    ///*ListV_content这个是之前的，没用了，你绑定到现在的上边*/
                }else if(msg.what==3){
                    Toast toast=Toast.makeText(getApplicationContext(), "验证码错误！请重新输入", Toast.LENGTH_SHORT);
                    //显示toast信息
                    toast.show();
                    getListName("2");
                }
            }
        };
        //change edit search
        edit_teacherName.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                getListName("2");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mFabUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRecyclerView.smoothScrollToPosition(0);
            }
        });

        mFabSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO
                Info1List.clear();//每次点击检索时将之前的列表清空
                loading.show();
                yzm_edit = edit_yzm.getText().toString();//获得输入的验证码
                final String technameSelected = spin_techname.getSelectedItem().toString();//获得下拉列表选中的教师名字
                //获得教师的编号value
                for (Object s : myMap.keySet()) {
                    if (myMap.get(s).toString().equals(technameSelected))
                        technameValue = s.toString();
                }
                if (fetchDataFromSqlite()) {//说明数据库中有数据
                    handler.sendEmptyMessage(2);
                } else {//否则，开启线程从网络上获取
                    new Thread() {
                        @Override
                        public void run() {
                            //Log.i("values", xqValue + "&" + technameValue);
                            String html_tableTeach = urlData.GetKBFBLessonSel(xqValue, technameValue, "1", yzm_edit);
                            try {
                                htmlParseJson = new HtmlParseJson();
                                JSONObject jsonObject = htmlParseJson.getClassInfo1(html_tableTeach);
                                //Log.i("json", jsonObject.toString());
                                Iterator<String> keysArr = jsonObject.keys();
                                for (Iterator it = keysArr; it.hasNext(); ) {
                                    String thiskey = "";
                                    if ((thiskey = (String) it.next()) != "") {
                                        Info1List = (ArrayList<ClassInfo1>) jsonObject.get(thiskey);
                                    }else{
                                        handler.sendEmptyMessage(3);
                                    }
                                }
                                handler.sendEmptyMessage(2);
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                }
            }
        });
        // set mToolbar
        setSupportActionBar(mToolbar);
        ActionBar ab = getSupportActionBar();
        if (ab != null) {
            ab.setDisplayHomeAsUpEnabled(true);
        }

        /*mAdapter = new CourseAdapter(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.lib_search_type));
        mSpinner.setAdapter(adapter);*/

    }

    //获取教师教师列表名
    private void getListName(String id) {
        loading.show();
        final String courseId = id;
        new Thread() {
            @Override
            public void run() {
                if (courseId == "1")
                    techname_edit = "";
                else
                    techname_edit = edit_teacherName.getText().toString();
                //访问网络获取教师姓名列表
                teachNameitems.clear();
                urlData = urlData.getInstance();
                urlData.GetCookie();
                String html_techName = urlData.GetXNXQKC(xqValue, techname_edit);
                htmlParseJson = new HtmlParseJson();
                myMap = htmlParseJson.OptiontoList(html_techName);
                //加载验证码
                bitmap_img = urlData.GetImage(1);//教师查询
                handler.sendEmptyMessage(1);
            }
        }.start();

    }

    //添加数据进入数据库
    private long addInfoToSqlite() {
        //实例化ContentValues对象并进行数据组装
        ContentValues values = new ContentValues();
        mDb = mHelper.getWritableDatabase();
        long temp =0;
        for (int i = 0; i < Info1List.size(); i++) {
            values.put("Teach_xq", xqValue);
            values.put("Teach_Name", technameValue);
            values.put("Teach_week", Info1List.get(i).getWeek());
            values.put("Teach_lesson", Info1List.get(i).getLesson());
            values.put("Teach_info", Info1List.get(i).getInfo());
            //插入数据
            temp = mDb.insert("Teacher_table", null, values);
            values.clear();
        }
        mDb.close();
        return temp;
    }
    //从数据库中读取数据
    private boolean fetchDataFromSqlite() {
        boolean flag = false;
        try {
            mDb = mHelper.getReadableDatabase();
            Cursor cursor = mDb.query("Teacher_table", null, "Teach_xq=? and Teach_Name=?", new String[]{xqValue, technameValue}, null, null, null);
            if (cursor.moveToFirst()) { //从数据库中取到数据
                flag = true;
                do {
                    String kc_week = cursor.getString(cursor.getColumnIndex("Teach_week"));
                    String kc_lesson = cursor.getString(cursor.getColumnIndex("Teach_lesson"));
                    String kc_info = cursor.getString(cursor.getColumnIndex("Teach_info"));
                    //取出了一条数据
                    ClassInfo1 cou = new ClassInfo1();
                    cou.setWeek(kc_week);
                    cou.setLesson(kc_lesson);
                    cou.setInfo(kc_info);
                    //Log.i("sqlite", cou.getInfo());
                    Info1List.add(cou);
                } while (cursor.moveToNext());
                cursor.close();
                mDb.close();
            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

}
